package com.renren.webmaven2.util;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * @author jizhong.yang
 */
public class CacheUtils implements Constants {
	private static CacheManager singletonManager = CacheManager.create();
	private static Cache basecache = null;
	static {
		Cache _cache = singletonManager.getCache(BASE_CACHE_KEY);
		if (_cache == null) {
			Cache memoryOnlyCache = new Cache(BASE_CACHE_KEY, 50000, false,
					true, 60 * 60 * 1000, 60 * 60 * 1000);
			singletonManager.addCache(memoryOnlyCache);
			basecache = memoryOnlyCache;
		}
	}

	public static void add(String key, Object value) {
		Element ele = new Element(key, value);
		basecache.put(ele);
	}

	public static Object get(String key) {
		if (basecache.isKeyInCache(key)) {
			Element ele = basecache.get(key);
			return ele == null ? null : ele.getObjectValue();
		}
		return null;
	}

	/**
	 * 
	 * @param prefix
	 * @param key
	 * @param value
	 */
	public static void add(String prefix, String key, Object value) {
		Cache cache = getCache(prefix);
		Element ele = new Element(key, value);
		cache.put(ele);
	}

	public static Object get(String prefix, String key) {
		Cache cache = getCache(prefix);
		if (cache.isKeyInCache(key)) {
			Element ele = cache.get(key);
			return ele == null ? null : ele.getObjectValue();
		}
		return null;
	}

	public static Cache getCache(String prefix) {
		Cache _cache = singletonManager.getCache(prefix);
		if (_cache == null) {
			_cache = new Cache(prefix, 1000, false, true, 60 * 60 * 1000,
					60 * 60 * 1000);
			singletonManager.addCache(_cache);
		}
		return _cache;
	}
}
